package cn.smxy.user.listener;

import cn.smxy.constant.UserConstant;
import cn.smxy.pojo.User;
import cn.smxy.user.service.UserService;
import cn.smxy.user.service.impl.UserServiceImpl;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

// 不能被spring管理
@Slf4j
public class ExcelUserListener implements ReadListener<User> {

    private List<User> cachedDataList = ListUtils.newArrayListWithExpectedSize(UserConstant.BATCH_COUNT);

    private UserService userService;

    public ExcelUserListener() {
        userService = new UserServiceImpl();
    }

    public ExcelUserListener(UserService userService) {
        this.userService = userService;
    }

    @Override
    public void invoke(User user, AnalysisContext analysisContext) {
        log.info("解析到一条数据:{}", user);
        cachedDataList.add(user);
        if(cachedDataList.size() >= UserConstant.BATCH_COUNT) {
            saveData();
            cachedDataList = ListUtils.newArrayListWithExpectedSize(UserConstant.BATCH_COUNT);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
        log.info("所有数据解析完成！");
    }

    private void saveData() {
        log.info("{}条数据，开始存储数据库！", cachedDataList.size());
        userService.saveExcel(cachedDataList);
        log.info("ExcelUserListener.saveData业务结束，结果为:{}","存储成功");
    }
}

